package com.sunseagear.common.base.mvc.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface BaseTreeMapper<T> extends BaseMapper<T> {


    /**
     * @param tableName: 节点表名
     * @param id: 节点ID
     * @param <ID>: ID类型
     * @return 包含当前节点的所有祖先节点
     */
    @Select("WITH RECURSIVE base_tree_parent_nodes AS (\n" +
            "    SELECT id\n" +
            "    FROM ${tableName}\n" +
            "    WHERE id = #{id}\n" +
            "    UNION ALL\n" +
            "    SELECT t.id\n" +
            "    FROM ${tableName} t\n" +
            "    JOIN base_tree_parent_nodes p ON t.id = p.parent_id)\n" +
            "SELECT * FROM base_tree_parent_nodes")
    <ID> List<ID> getParentIdsAndSelf(String tableName, ID id);


    /**
     * @param tableName: 节点表名
     * @param id: 节点ID
     * @param <ID>: ID类型
     * @return 包含当前节点的所有子孙节点
     */
    @Select("WITH RECURSIVE base_tree_sub_nodes AS (\n" +
            "    SELECT id FROM ${tableName} WHERE id = #{id}\n" +
            "    UNION ALL\n" +
            "    SELECT tn.id FROM ${tableName} tn\n" +
            "    JOIN base_tree_sub_nodes sn ON tn.parent_id = sn.id)\n" +
            "SELECT id FROM base_tree_sub_nodes;")
    <ID> List<ID> getChildrenIdsAndSelf(String tableName, ID id);

}
